package com.itheima.advantagesup.service.impl;

import com.itheima.advantagesup.entity.SysMenu;
import com.itheima.advantagesup.mapper.SysMenuMapper;
import com.itheima.advantagesup.service.SysMenuService;
import com.itheima.advantagesup.vo.MenuVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liudo
 * @version 1.0
 * @project advantages-up
 * @date 2023/9/9 19:59:21
 */
@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl implements SysMenuService {

    private final SysMenuMapper sysMenuMapper;

    @Override
    public List<MenuVO> allData() {
        List<SysMenu> sysMenuList = sysMenuMapper.selectListByPid(0);
        return sysMenuList.stream()
                .map(this::getChildren)
                .collect(Collectors.toList());
    }

    @Override
    public MenuVO rowInfo(Integer id) {
        SysMenu sysMenu = sysMenuMapper.selectById(id);
        return sysMenu.transformVO();
    }

    @Override
    public void update(SysMenu sysMenu) {
        sysMenu.setUpdateDate(LocalDateTime.now());
        sysMenuMapper.update(sysMenu);
    }

    @Override
    public void save(SysMenu sysMenu) {
        sysMenu.setCreateDate(LocalDateTime.now());
        sysMenu.setUpdateDate(LocalDateTime.now());
        sysMenuMapper.insert(sysMenu);
    }

    /**
     * 递归获取孩子列表
     *
     * @param sysMenu sys菜单
     * @return {@link MenuVO}
     */
    private MenuVO getChildren(SysMenu sysMenu) {
        List<SysMenu> children = sysMenuMapper.selectListByPid(sysMenu.getId());
        if (CollectionUtils.isEmpty(children)) {
            return sysMenu.transformVO();
        }
        List<MenuVO> menuVOList = children.stream().map(this::getChildren)
                .collect(Collectors.toList());
        MenuVO menuVO = sysMenu.transformVO();
        menuVO.setChildren(menuVOList);
        return menuVO;
    }
}
